package com.gzcssutils;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;

import java.util.Date;
import java.util.logging.Logger;

/**
 * 线程获取access_token
 */
public class AccessTokenThread {

    private static Logger log = Logger.getLogger("com.utils.AccessTokenThread");

    public final static String _access_token_url_qx = "http://address:port/cgi-bin/gettoken?corpid=APPID&corpsecret=APPSECRET";

    public static Cache<String,Object> cache = CacheUtil.newFIFOCache(3);
    /**
     * 获取access_token
     * @return
     */
    public static AccessToken getAccessToken()  {
        AccessToken accessToken  = new AccessToken();
        String requestUrl = _access_token_url_qx.replace("address:port", Constant.url).replace("APPID", Constant.AppId).replace("APPSECRET", Constant.APPSECRET);
        log.info("取得URL:"+requestUrl);
        JSONObject jsonObject = HttpUtil.httpRequest(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken.setToken(jsonObject.getStr("access_token"));
                accessToken.setCreateTime(new Date());
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
                cache.put("access_token",accessToken);
                log.info(jsonObject.toString());
            } catch (JSONException e) {
                accessToken = null;
                //添加错误日志信息记录
                log.info("获取token失败 errcode:{" + jsonObject.get("errcode") +"} errmsg:{"+ jsonObject.get("errmsg") +"}");
            }
        }
        return accessToken;
    }

    public static String getCacheToken() {
        String token = "";
        if(null != cache.get("access_token")) {
            AccessToken accessToken = (AccessToken)cache.get("access_token");
            Long startTime = accessToken.getCreateTime().getTime();
            long useTime = ((System.currentTimeMillis() - startTime)/1000)/3600;
            if(accessToken.getExpiresIn() > useTime) {
                token = accessToken.getToken();
            }else {
               log.info("token过期了");
               cache.remove("access_token");
               return getAccessToken().getToken();
            }

        }else {
            return getAccessToken().getToken();
        }
        return token;
    }



    public static void main(String[] args) {
        getAccessToken();
        log.info("从cache中取token:" + getCacheToken());
    }

}
